import os,wave,audioop

def resample_wav(src, dst, inrate, outrate, inchannels=1, outchannels=1):

    print ('[resample_wav]','src:',src)

    if not os.path.exists(src):
        print ('Source not found!')
        return False

    if not os.path.exists(os.path.dirname(dst)):
        os.makedirs(os.path.dirname(dst))

    try:
        s_read = wave.open(src, 'rb')
        params = s_read.getparams()
        nchannels, sampwidth, framerate, nframes = params[:4]
        print(nchannels,sampwidth, framerate,nframes)
        s_write = wave.open(dst, 'wb')
    except:
        print ('Failed to open files!')
        return False

    n_frames = s_read.getnframes()
    data = s_read.readframes(n_frames)

    try:
        converted = audioop.ratecv(data, 2, inchannels, inrate, outrate, None)
        if outchannels == 1 and inchannels != 1:
            converted = audioop.tomono(converted[0], 2, 1, 0)
    except:
        print ('Failed to downsample wav')
        return False

    try:
        s_write.setparams((outchannels, 2, outrate, 0, 'NONE', 'Uncompressed'))
        s_write.writeframes(converted[0])
    except Exception as e:
        print(e)
        print ('Failed to write wav')
        return False

    try:
        s_read.close()
        s_write.close()
    except:
        print ('Failed to close wav files')
        return False

    return True


def merge_wavs(src_dir, output_file):
    files = os.listdir(src_dir)
    wav_files = [file for file in files if file.endswith('.wav')]
    streams = []
    for wav_file in wav_files:
        with wave.open(os.path.join(src_dir, wav_file), 'rb') as f:
            streams.append(f.readframes(f.getnframes()))

    merged_audio = b''.join(streams)

    with wave.open(output_file, 'wb') as f:
        f.setnchannels(1)
        f.setsampwidth(2)
        f.setframerate(48000)
        f.writeframes(merged_audio)

def resample_wavs(src_dir, output_dir):
    files = os.listdir(src_dir)
    old_files = [file for file in files if file.endswith('.wav')]
    for old_file in old_files:
        print('[resample_wavs]','old_file:',old_file)
        filename = os.path.basename(old_file)
        abs_path = os.path.join(src_dir, old_file)
        dirname = os.path.dirname(abs_path)
        # print('filename:',filename)
        print('[resample_wavs]', 'abs_path:',abs_path)
        # print('dirname:',dirname)
        if old_file.endswith('.wav') == 0:
            continue
        with wave.open(os.path.join(src_dir, old_file), 'rb') as wave_file:
            inrate = wave_file.getframerate()
            inchannels = wave_file.getnchannels()
            print('[resample_wavs]','inrate:',inrate)
            print('[resample_wavs]','inchannels:',inchannels)
            new_path = os.path.join(output_dir, filename);
            print('[resample_wavs]','old_path:',abs_path)
            print('[resample_wavs]','new_path:',new_path)
            resample_wav(abs_path, new_path, inrate, 48000, inchannels, 1)



def wav_to_pcm(wav_file_path, pcm_file_path):
    with wave.open(wav_file_path, 'rb') as wav_file:
        # 获取音频参数
        num_channels = wav_file.getnchannels()
        sample_width = wav_file.getsampwidth()
        framerate = wav_file.getframerate()
        num_frames = wav_file.getnframes()
        # 读取音频数据
        pcm_data = wav_file.readframes(num_frames)
    with open(pcm_file_path, 'wb') as pcm_file:
        pcm_file.write(pcm_data)



def pcm_to_wav(pcm_file_path, wav_file_path):

    # 假设你有一个PCM数据文件，这里只是示例如何读取和转换
    with open(pcm_file_path, "rb") as pcm_file:
        pcm_data = pcm_file.read()

        wav_file = wave.open(wav_file_path, "wb")
        wav_file.setnchannels(1)
        wav_file.setsampwidth(2)  # 16位深度，每个样本2字节
        wav_file.setframerate(48000)
        wav_file.writeframes(pcm_data)
        wav_file.close()
